package hu.monitor.remoting.transport;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public abstract class MarshallerClient implements Client {
	private static Logger log = LoggerFactory.getLogger(MarshallerClient.class);

	private final Marshaller marshaller;

	public MarshallerClient(final Marshaller marshaller) {
		this.marshaller = marshaller;
	}

	@Override
	public Object send(final Object object) throws Exception {
		OutputStream output = null;
		InputStream input = null;
		try {
			output = this.getOutputStream();
			this.marshaller.marshall(object, output);
			output.flush();

			input = this.getInputStream();
			return this.marshaller.unmarshall(input);
		} finally {
			this.closeStreams(input, output);
		}
	}

	protected abstract InputStream getInputStream() throws IOException;

	protected abstract OutputStream getOutputStream() throws IOException;

	protected void closeInputStream(final InputStream input) throws IOException {
		input.close();
	}

	protected void closeOutputStream(final OutputStream output) throws IOException {
		output.close();
	}

	private void closeStreams(final InputStream input, final OutputStream output) {
		if (input != null) {
			try {
				this.closeInputStream(input);
			} catch (final IOException ex) {
				log.error(ex.getMessage(), ex);
			}
		}

		if (output != null) {
			try {
				this.closeOutputStream(output);
			} catch (final IOException ex) {
				log.error(ex.getMessage(), ex);
			}
		}
	}

}
